/**
 * @authors tanqichao
 * @date    2017-06-20 13:59:27
 * @module  高级设置 - 投放场景
 */

import React, { Component, PropTypes } from 'react';
import { Radio, Checkbox, Modal, Tree } from 'antd';
import Styles from './Scene.less'; // 复用下，不想新建了

const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;
const TreeNode = Tree.TreeNode;

class Scene extends Component {
  constructor(props) {
    super(props)
    this.state = {
      visible: false,
      checkedValue: []
    }
  }

  // 渲染媒体列表
  renderScene = () => {
    const { sceneCodes, sceneList, sceneComplete } = this.props
		const loop = data => data.map((item) => {
      if (item.children && item.children.length) {
        return <TreeNode key={item.code} title={item.name} >{loop(item.children)}</TreeNode>
      }
      return <TreeNode key={item.code} title={item.name} />
		})
    const handleCheck = (checkedKeys) => {
      this.setState({
        checkedValue: checkedKeys
      })
    }

		return (
			<Tree
	    	checkable
        onCheck={handleCheck}
        defaultCheckedKeys={sceneCodes.length > 0 ? sceneCodes.join(',').split(',') : []}
	    >
				{loop(sceneList)}
			</Tree>
		)
  }

  // 弹窗
  showSceneList = () => {

    const { sceneComplete } = this.props

    const hide = () => {
      this.setState({visible: false})
    }
    const setScene = () => {
      sceneComplete(this.state.checkedValue)
      this.setState({visible: false})
    }

    return (
      <Modal
        title="投放场景"
        wrapClassName="scene"
        onCancel={hide}
        onOk={setScene}
        maskClosable={false}
        visible={this.state.visible}
      >
        <div className="options">
          {this.renderScene()}
        </div>
      </Modal>
    )
  }

  render() {
    const { sceneCodes, sceneList, sceneComplete } = this.props
    const handleChange = (e) => {
      const checked = e.target.value
      if (checked === 1) {
        sceneComplete([])
      }
      this.setState({
        visible: checked === 2 ? true : false
      })
    }
    const modify = () => {
      this.setState({visible: true})
    }

    return (
      <span>
        <RadioGroup
          onChange={handleChange}
          value={sceneCodes && !!sceneCodes.length ? 2 : 1}
        >
          <Radio value={1}>不限</Radio>
          <Radio value={2}>指定场景</Radio>
        </RadioGroup>
        {(sceneCodes && !!sceneCodes.length) ? <a onClick={modify}>更改</a> : null}
        {sceneList && sceneList.length && this.showSceneList()}
      </span>
    )
  }
};

export default Scene;
